<template>
  <div class="container" ref="container" @scroll="handleScroll">
    <div class="task_header">
      <div class="top_title">
        <div class="top_title_back" @click="onClickLeft">
          <i class="iconfont icon-back"></i>
        </div>
        <div class="top_title_val">{{ title }}</div>
        <div class="task_transbox" @click="handleIntro">
          <div>统计说明</div>
        </div>
      </div>
    </div>
    <div class="search">
      <div>
        <van-field
          v-model="requestParams.brandName"
          name="品牌"
          label="品牌"
          input-align="right"
          placeholder="请选择"
          readonly
          @click="handleSelect('brandId', 'brandName')"
        >
          <template #button v-if="requestParams.brandName">
            <van-icon name="close" class="close-icon" @click.stop="handleClear('brandId', 'brandName')" />
          </template>
        </van-field>
        <van-field
          v-model="requestParams.fixCenterName"
          name="维修中心"
          label="维修中心"
          input-align="right"
          readonly
          placeholder="请选择"
          @click="handleSelect('fixCenterId', 'fixCenterName')"
        >
          <template #button v-if="requestParams.fixCenterName">
            <van-icon name="close" class="close-icon" @click.stop="handleClear('fixCenterId', 'fixCenterName')" />
          </template>
        </van-field>
      </div>
      <van-field
        v-model="requestParams.taskStartCreateTime"
        label="开始时间"
        :placeholder="'请选择'"
        input-align="right"
        right-icon="arrow"
        readonly
        @click="handleSelectTime('taskStartCreateTime')"
        label-width="160px"
      />
      <van-field
        v-model="requestParams.taskEndCreateTime"
        label="结束时间"
        :placeholder="'请选择'"
        input-align="right"
        right-icon="arrow"
        readonly
        label-width="160px"
        @click="handleSelectTime('taskEndCreateTime')"
      />
      <div class="timebox">
        <!-- <van-field
          v-model="requestParams.taskTypeName"
          name="任务类型"
          label="任务类型"
          input-align="right"
          placeholder="请选择"
          readonly
          right-icon="arrow"
          @click="handleSelect('taskTypeId', 'taskTypeName')"
        />-->
        <!-- <van-field
          name="radio"
          label="统计类型"
          input-align="right"
        >
          <template #input>
            <van-radio-group
              v-model="requestParams.countType"
              direction="horizontal"
            >
              <van-radio name="person">按人员</van-radio>
              <van-radio name="taskType">按任务类型</van-radio>
            </van-radio-group>
          </template>
        </van-field>-->
        <van-popup v-model="showSelectPicker" position="bottom">
          <van-picker show-toolbar :columns="columns" @confirm="handleSelectConfirm" @cancel="showSelectPicker = false" value-key="name" />
        </van-popup>
        <!-- 时间选择 -->
        <van-popup v-model="showPickerDate" position="bottom">
          <van-datetime-picker v-model="currentDate" type="year-month" @cancel="onCancelDate" @confirm="onConfirmDate" :formatter="formatter" />
        </van-popup>
      </div>
    </div>
    <div class="tableData">
      <div class="tableDatabox">
        <table>
          <tr>
            <th>{{ requestParams.countType == 'person' ? '人员' : '维修中心' }}</th>
            <th>本月已回场台次</th>
            <th>本月已完工台次</th>
            <th>本月计奖台次</th>
<!--            <th>活跃客户约回数</th>-->
<!--            <th>准流失客户约回数</th>-->
<!--            <th>流失客户约回数</th>-->
            <th>本月任务数</th>
            <th>本月已处理</th>
            <th>本月任务车辆数</th>
            <th>本月处理车辆数</th>
            <th>本月外呼客户数</th>
            <th>确认入场时间台次</th>
            <th>确认入场时间占比</th>
            <th>招揽进场率</th>

            <!-- <th>成功回场率</th> -->
            <!-- <th>本月已贡献产值</th> -->
          </tr>
          <tbody v-if="dataList && dataList.length != 0">
            <tr v-for="(item, index) in dataList" :key="index">
              <!-- <td class="tab_item">
              {{ item.fixCenterName }}
              </td>-->
              <td class="tab_item">{{ item.personName }}</td>
              <td>{{ item.turnCount }}</td>
              <td>{{ item.finishCount }}</td>
              <td>{{ item.jjcount }}</td>
<!--              <td>{{ item.Hykh_Hy_Count }}</td>-->
<!--              <td>{{ item.Zlskh_Yh_Count }}</td>-->
<!--              <td>{{ item.Lskh_Yh_Count }}</td>-->
              <td>{{ item.taskCount }}</td>
              <td>{{ item.dealCount }}</td>
              <td>{{ item.carCount }}</td>
              <td>{{ item.dealcarcount }}</td>
              <td>{{ item.callCount }}</td>
              <td>{{ item.successCount }}</td>
              <td>{{ item.successPercent }}</td>
              <td>{{ item.inPercent }}</td>
              <!-- <td>{{ item.turnPercent }}</td> -->
              <!-- <td>{{ item.resultValue }}</td> -->
            </tr>
          </tbody>

          <tr class="last_item">
            <td class="tab_item">{{ lastObj.name }}</td>
            <td>{{ lastObj.totTurnCount }}</td>
            <td>{{ lastObj.totFinishCount }}</td>
            <td>{{ lastObj.totJJcount }}</td>
<!--            <td>{{ lastObj.tot_Hykh_Hy_Count }}</td>-->
<!--            <td>{{ lastObj.tot_Zlskh_Yh_Count }}</td>-->
<!--            <td>{{ lastObj.tot_Lskh_Yh_Count }}</td>-->
            <td>{{ lastObj.totTaskCount }}</td>
            <td>{{ lastObj.totDealCount }}</td>
            <td>{{ lastObj.totCarCount }}</td>
            <td>{{ lastObj.totDealcarcount }}</td>
            <td>{{ lastObj.totCallCount }}</td>
            <td>{{ lastObj.totSuccessCount }}</td>
            <td>{{ lastObj.totSuccessPercent }}</td>
            <td>{{ lastObj.totInPercent }}</td>

            <!-- <td>{{ lastObj.totTurnPercent }}</td> -->
            <!-- <td>{{ lastObj.totResultValue }}</td> -->
          </tr>
        </table>
      </div>
    </div>
    <div class="pagebox">
      <!-- <div class="pre_btn" :class="requestParams.pageNo == 1 ? 'disable' : ''" @click="handlePage('pre')">上一页</div> -->
      <div class="next_btn" v-if="!moreFlag" @click="handlePage('next')" :class="dataList && dataList.length == 0 ? 'disable' : ''">加载更多</div>
      <div v-else class="no_tips">没有更多了...</div>
    </div>

    <div class="loading" v-if="loading">
      <van-loading size="30px" class="loadbox" color="#fff" text-color="#fff">加载中...</van-loading>
      <div class="mask"></div>
    </div>
  </div>
</template>

<script>
import taskApi from '@/api/taskApi'
import commonApi from '@/api/commonApi'
import { getCookies, getCurrentMonth } from '@/utils/util.js'
import { Toast } from 'vant'
import sellManageApi from '@/api/sellManageApi'

export default {
  name: 'taskData',
  components: { Toast },
  data() {
    return {
      columns: [],
      showSelectPicker: false,
      requestParams: {
        countType: 'person', //必填，person,taskType，对应按照人员或者任务类型
        brandId: '', //品牌ID
        pageNo: 1, //页数，每页默认500条
        fixCenterId: '', //维修中心IDString
        taskStartCreateTime: getCurrentMonth(), //任务开始创建时间 yyyy-MM-dd
        taskEndCreateTime: getCurrentMonth(), //任务结束创建时间 yyyy-MM-dd
        taskTypeId: '', //任务类型ID，
        userId: getCookies('userId'), //用户ID，必填，String
        pageNums: 10,
      },

      repairCenterList: [
        { name: '厦门路虎', code: '1' },
        { name: '厦门捷豹', code: '2' },
      ],
      serviceList: [
        { name: '黄某某', code: '1' },
        { name: '张某某', code: '2' },
      ],

      timeField: '',
      field: '',
      fieldName: '',
      showPickerDate: false,
      currentDate: new Date(),
      dataList: [],
      lastObj: [],
      taskTypeList: [],
      fixCenterList: [],
      brandList: [],
      loading: false,
      btnType: '',
      observer: null,
      moreFlag: false,
      title: '',
      routerBillId: '',
    }
  },
  watch: {
    requestParams: {
      handler: function (val, oldVal) {
        if (val.brandId || val.fixCenterId || val.taskStartCreateTime || val.taskEndCreateTime || val.taskTypeId || val.countType) {
        }
      },
      deep: true,
      immediate: false,
    },
  },

  mounted() {
    if (this.$route.query && this.$route.query.countType) {
      this.requestParams.countType = this.$route.query.countType
      this.title = this.$route.query.countType == 'person' ? '招揽情况表_人员' : '招揽情况表_门店'
      this.routerBillId = this.$route.query.countType == 'person' ? 'ZSIAABJZ0KCcNUO1' : 'ZSIAABJZ2HCcNUO1'
      // document.title=this.title
    }

    this.getBrandList()
    this.getTaskType()
    this.loadData()
  },

  methods: {
    initData() {
      this.moreFlag = false
      this.dataList = []
      this.lastObj = {}
      this.requestParams.pageNo = 1
      this.loadData()
    },
    handleScroll(event) {
      const { scrollTop, clientHeight, scrollHeight } = event.target
      if (scrollTop + clientHeight >= scrollHeight) {
        console.log('滚动到底部了！')
        // this.loadData()
      }
    },

    handlePage(type) {
      this.loadData()
      // if (type == 'pre') {
      //   if (this.requestParams.pageNo != 1) {
      //     this.requestParams.pageNo -= 1
      //   } else {
      //     return
      //   }
      // } else if (type == 'next') {
      //   if (this.dataList.length != 0) {
      //     this.requestParams.pageNo += 1
      //   }
      // }
      // this.btnType = type
    },
    handleClear(field, fieldName) {
      if (field == 'brandId') {
        this.requestParams.fixCenterId = ''
        this.requestParams.fixCenterName = ''
      }
      this.requestParams[field] = ''
      this.requestParams[fieldName] = ''
      this.initData()
    },
    onClickLeft() {
      this.$router.go(-1)
    },
    // 选择下拉
    handleSelect(field, fieldName) {
      if (field == 'taskTypeId') {
        this.columns = this.taskTypeList
      } else if (field == 'brandId') {
        this.columns = this.brandList
        this.requestParams.fixCenterId = ''
        this.requestParams.fixCenterName = ''
      } else if (field == 'fixCenterId') {
        if (!this.requestParams.brandId) {
          Toast('请先选择品牌')
          return
        }
        this.columns = this.fixCenterList
      }
      this.field = field
      this.fieldName = fieldName
      this.showSelectPicker = true
    },

    // 获取维修中心
    getMainFixCenter() {
      sellManageApi
        .secondHandCarFacade({
          method: 'getShowOrgOrFixCenterByBandId',
          orgKey: 'fixCenter', //showOrg展厅，fixCenter维修中心
          isAll: 2, //传1代表获取所有数据，否则获取当前用户有权限的
          brandId: this.requestParams.brandId, //品牌ID，必填，String
        })
        .then((res) => {
          this.fixCenterList = res.data
        })
    },
    // 获取品牌
    getBrandList() {
      sellManageApi
        .secondHandCarFacade({
          method: 'getShowOrgByUser',
          orgKey: 'brandAll',
        })
        .then((res) => {
          if (res.code == 1) {
            this.brandList = res.data
          }
        })
    },

    // 获取任务类型
    getTaskType() {
      commonApi.getTaskType({ userId: this.requestParams.userId }).then((res) => {
        this.taskTypeList = res.data
      })
    },

    // 日期组件自定义格式
    // formatter(type, val) {
    //   if (type === 'year') {
    //     return `${val}年`;
    //   } else if (type === 'month') {
    //     return `${val}月`;
    //   }
    //   return val;
    // },
    formatter(type, value) {
      if (type === 'year') {
        this.value1 = value // 可以拿到当前点击的数值
        return `${value}年`
      } else if (type === 'month') {
        this.value2 = value
        return `${value}月`
      }
      this.value3 = value
      return `${value}日`
    },

    // 获取list名称
    getFieldName(list, key, val) {
      if (list && list.length > 0) {
        let obj = list.filter((item) => {
          return item[key] == val
        })
        if (obj.length > 0) {
          return obj[0].name
        }
      }
      return null
    },
    // 选择下拉确认
    handleSelectConfirm(value, index) {
      this.requestParams[this.field] = value.billId
      this.requestParams[this.fieldName] = value.name
      if (this.field == 'brandId') {
        this.getMainFixCenter()
      }
      this.initData()

      this.showSelectPicker = false
    },
    // 时间筛选
    handleSelectTime(field) {
      this.timeField = field
      this.showPickerDate = true
    },
    // 时间确认
    onConfirmDate() {
      this.requestParams[this.timeField] = `${this.value1}-${this.value2}` // 字符串拼接 结果入2020-07-03
      this.onCancelDate()
      this.initData()
    },
    onCancelDate() {
      this.showPickerDate = false
    },
    isDateGreater(dateStr1, dateStr2) {
      const date1 = new Date(dateStr1)
      const date2 = new Date(dateStr2)
      return date1 > date2
    },
    handleIntro() {
      this.$router.push({
        path: '/knowledgeBaseDetail',
        query: { billId: this.routerBillId },
      })
    },
    // 获取列表
    loadData() {
      // if (this.btnType == 'next') {
      //   if (this.dataList.length == 0 && this.requestParams.pageNo != 1) {
      //     return
      //   }
      // } else if (this.btnType == 'next') {
      //   if (this.dataList.length == 0) {
      //     return
      //   }
      // }

      this.loading = true
      let params = JSON.parse(JSON.stringify(this.requestParams))
      params.taskStartCreateTime = params.taskStartCreateTime ? params.taskStartCreateTime + '-01' : ''
      params.taskEndCreateTime = params.taskEndCreateTime ? params.taskEndCreateTime + '-01' : ''

      if (this.isDateGreater(this.requestParams.taskStartCreateTime, this.requestParams.taskEndCreateTime)) {
        Toast('结束时间不能比开始小,请重新选择')
        this.loading = false
        return
      }

      taskApi.taskDataCal({ ...params }).then((res) => {
        this.loading = false
        if (res.data && res.data.length != 0) {
          this.requestParams.pageNo += 1
          this.dataList = this.dataList.concat(res.data || [])
          this.lastObj = res.totalData
        } else {
          this.moreFlag = true
        }
      })
    },
  },
}
</script>

<style lang="less" scoped="">
.search {
  margin-top: 50px;
}
.container {
  overflow-y: scroll;
  height: 100vh;
}
.pagebox {
  display: inline-block;
  margin: auto;
  margin-top: 20px;
  margin-bottom: 20px;
  text-align: center;
  width: 100%;
  .pre_btn,
  .next_btn {
    // background: #d1d1d1;
    color: #fff;
    background: linear-gradient(316deg, #3975c6 0%, #71a4ea 100%);

    // border: 1px solid #d1d1d1;
    font-size: 14px;
    padding: 10px;
    text-align: center;
    border-radius: 5px;
    width: 100px;
    margin: auto;
    &.disable {
      background: #d1d1d1;
      color: #999;
    }
  }
  .no_tips {
    color: #666;
    font-size: 12px;
  }
  .btn {
  }
}
.home {
  // background: #f3f3f3;
}
.timebox {
  /deep/.van-cell::after {
    border: none;
  }
  .time_item {
    /deep/.van-field__control--right {
      border: 1px solid #d1d1d1;
      padding: 0.1rem 0;
      text-align: center;
      border-radius: 3px;
    }
  }
}

.timebox {
  /deep/.van-cell::after {
    border: none;
  }
  .time_item {
    /deep/.van-field__control--right {
      border: 1px solid #d1d1d1;
      padding: 0.1rem 0;
      text-align: center;
      border-radius: 3px;
    }
  }
}

.tableData {
  margin: 0 16px;
  // height: 500px;
  border-collapse: collapse;
  text-align: center;
  // height: auto; /* 自动计算高度 */
  border-radius: 5px;
  overflow-x: hidden;

  .tableDatabox {
    overflow-x: scroll;
  }

  table {
    min-width: 800px;
    font-size: 0.24rem;
    border: none;
    width: 100%;
  }
  .last_item td {
    font-weight: bold;
  }

  .tab_item {
    background: #f1f1f1;
  }
  tr > td:first-child {
    position: sticky;
    left: 0;
    z-index: 1;
    background: #3975c6;

    color: #fff;
  }
  tr > th:first-child {
    position: sticky;
    left: 0;
    z-index: 1;
    background: #3975c6;
    color: #fff;
  }

  tr {
    th {
      position: sticky; /* 将表头固定在位置 */
      top: 0; /* 与容器顶部对齐 */
      font-size: 12px;
      border: 1px solid #fff;
      padding: 0.2rem 0;
      background: #3975c6;
      color: #fff;
      font-weight: bold;
    }
    td {
      padding: 0.1rem 0;
      border: 1px solid #f1f1f1;
      color: #333;
      font-size: 12px;
    }
  }
}
@media screen and (min-width: 375px) {
  .tableData {
    table {
      // min-width: 100%;
    }
  }
}
.task_header {
  background: url('~@/assets/images/title_bg.png') no-repeat center;
  font-size: 0.24rem;
  height: 50px;
  background-size: 100% 100%;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 9;

  .top_title {
    position: relative;
    width: 100%;
    height: 50px;

    .top_title_back {
      position: absolute;
      left: 10px;
      line-height: 50px;
      color: #fff;
    }

    .top_title_val {
      text-align: center;
      line-height: 50px;
      color: #fff;
      font-weight: bold;
      font-size: 16px;
    }
    .task_transbox {
      position: absolute;
      right: 10px;
      top: 20px;
      color: #fff;
      z-index: 10;
      font-weight: 400;
      font-size: 12px;
      text-align: center;
      .task_trans {
        width: 24px;
        display: block;
        margin: auto;
      }
    }
  }

  .task_header_data {
    .task_header_date {
      margin-bottom: 10px;
      display: flex;
      align-items: center;

      .task_header_date_w {
        width: 12.5%;
      }

      .task_header_date_item {
        width: 12.5%;
        text-align: center;
        color: #fff;
        font-size: 14px;
      }
    }

    .task_header_followData {
      display: flex;
      align-items: center;
      color: #fff;
      margin-bottom: 10px;

      .task_header_followData_tt {
        width: 12.5%;
        text-align: center;
      }

      .task_header_followData_item {
        width: 12.5%;
        text-align: center;
        font-size: 12px;
        font-weight: bold;
      }
    }
  }
}
</style>
